import base64

from fastapi import APIRouter
from pydantic import BaseModel

from app.core.dependencies import store_captcha
from app.utils.captcha import generate_captcha_image
from app.utils.md5_util import str_to_md5
from app.utils.response import success_response

router = APIRouter()


class CaptchaVerifyRequest(BaseModel):
    captcha_id: str
    code: str


@router.get("/captcha", summary="获取图形验证码")
async def get_captcha():
    """生成并返回图形验证码，同时返回验证码ID用于后续验证"""
    image_buf, code = generate_captcha_image()
    captcha_id = store_captcha(code)
    image_data = image_buf.getvalue()
    image_base64 = base64.b64encode(image_data).decode("utf-8")
    return success_response(
        data={
            "base64": "data:image/png;base64," + image_base64,
            "key": captcha_id,
            "md5": str_to_md5(image_base64)
        })
